﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace WebApplication4
{
    public partial class _Default : Page
    {
        private static DataTable table = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillData();
            }
        }

        private void FillData()
        {
            var sql = "select * from Student";
            table=DbHelper.GetData(sql);
            GridView1.DataSource = table;
            GridView1.DataBind();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            FillData();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            FillData();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var idStr = Getcellvaules(e.RowIndex, 0);
            var isOk = int.TryParse(idStr, out int id);
            var name = Getcellvaules(e.RowIndex, 1);
            var sex = Getcellvaules(e.RowIndex, 2);
            var remark = Getcellvaules(e.RowIndex, 3);
            if (isOk)
            {
                var sql = string.Format("update Student set StuName='{0}',StuSex='{1}',Remark='{2}'where Id='{3}'", name, sex, remark, id);
                DbHelper.ADU(sql);
            }
            else
            {
                var sql = string.Format("insert into Student(StuName,StuSex,Remark)values('{0}','{1}','{2}')", name, sex, remark);
                DbHelper.ADU(sql);
            }
           
            GridView1.EditIndex = -1;
            FillData();
        }

        private string Getcellvaules(int rowIndex, int v)
        {
            var control = GridView1.Rows[rowIndex].Cells[v];
            var dt = control.Controls.Count>0?((TextBox)control.Controls[0]).Text:control.Text;
            return dt;
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = Getcellvaules(e.RowIndex, 0);
            var sql = string.Format("delete from Student where Id='{0}'", id);
            DbHelper.ADU(sql);
            GridView1.EditIndex = -1;
            FillData();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            var dt= table.Copy();
            dt.Rows.Add(dt.NewRow());
            GridView1.DataSource = dt;
            GridView1.DataBind();
            GridView1.EditIndex = dt.Rows.Count - 1;
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}